package com.thread.worker_thread;

/**
 * @author leon(liangzou0318@gmail.com)
 * @date 2012-10-20
 * @filaname Channel.java
 */
public class Channel {
 private static final int MAX_REQUEST=100;
 private final Request[] requestQueue;
 private int tail;
 private int head;
 private int count;
 private final WorkThread[] threadPool;
 public Channel(int threads) {
	this.requestQueue=new Request[MAX_REQUEST];
	this.count=0;
	this.head=0;
	this.tail=0;
	threadPool=new WorkThread[threads];
	for(int i=0;i<threadPool.length;i++){
		threadPool[i]=new WorkThread("Work "+i,this);
	}
}
public void startWork(){
	for(int i=0;i<threadPool.length;i++){
		threadPool[i].start();
	}
}
public synchronized void putRequest(Request request) {
	while(count>=requestQueue.length){
		try {
			wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	requestQueue[tail]=request;
	tail=(tail+1)%requestQueue.length;
	count++;
	notifyAll();
}
public synchronized Request takeRequest(){
	while(count<=0){
		try {
			wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	Request request =requestQueue[head];
	head=(head+1)%requestQueue.length;
	count--;
	notifyAll();
	return request;
	
	
}
}
